package com.java2108.hetong.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.bw.zhanggm.common.AjaxResult;
import com.java2108.hetong.entity.HtContract;
import com.java2108.hetong.service.IHtContractService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricDetailQuery;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

@Slf4j
@RestController
@RequestMapping("hetong/activiti")
public class ActivitiController {

    //工作流发布
    @Autowired
    RepositoryService repositoryService;

    //提交任务到工作流
    @Autowired
    RuntimeService runtimeService;

    //我的代办 审核
    @Autowired
    TaskService taskService;

    //查询历史关联关系
    @Autowired
    HistoryService historyService;

    @Autowired
    private IHtContractService contractService;


    @GetMapping("deploy")
    public void deploy() throws FileNotFoundException {
//        InputStream stream = ResourceUtil.getStream("bpmn/hetong.bpmn20.zip");
        repositoryService.createDeployment()
                .addClasspathResource("bpmn/hetong.bpmn20.xml")
                .addClasspathResource("bpmn/hetong.bpmn20.png")
//                .addZipInputStream(new ZipInputStream(stream))
                .name("合同审核")
                .key("hetong")
                .deploy();

    }

    @GetMapping("test")
    public void test() {
        //查询部署的报销流程定义
        Deployment hetong = repositoryService.createDeploymentQuery().deploymentKey("hetong").singleResult();
        log.info("hetong:{}", hetong);
        //启动报销流程
        Map<String, Object> variables = new HashMap<>();
        variables.put("caiwu", "zhangsan");
        variables.put("fawu", "lisi");
        ProcessInstance hetong1 = runtimeService.startProcessInstanceByKey("hetong", "1",variables);
        //查询历史报销流程
        HistoricDetailQuery historicDetailQuery = historyService.createHistoricDetailQuery().activityInstanceId(hetong1.getProcessInstanceId());
        HistoricProcessInstance hetong2 = historyService.createHistoricProcessInstanceQuery().processDefinitionKey("hetong").processInstanceBusinessKey("1").singleResult();
        //挂起报销流程实例
        hetong1.isSuspended();
        runtimeService.suspendProcessInstanceById(hetong.getId());
        //激活报销流程实例
        runtimeService.activateProcessInstanceById(hetong.getId());

    }


    @PostMapping("startProcessInstanceById")
    public AjaxResult startProcessInstanceById(@RequestBody HtContract htContract) {
        //定义流程变量，如果流程图，直接写成zhangsan、lisi之类的，就不需要写variables
        Map<String, Object> variables = new HashMap<>();
        variables.put("caiwu", "zhangsan");
        variables.put("fawu", "lisi");
        //提交到工作流
//        runtimeService.startProcessInstanceById("hetong:1:4dc24916-d847-11ee-88ac-005056c00001", htContract.getId() + "", variables);
        runtimeService.startProcessInstanceByKey("hetong", htContract.getId() + "", variables);

        return AjaxResult.success("提交成功");
    }


    @Autowired
    private HttpServletRequest request;

    /**
     * 我的代办 列表
     * @return
     */
    @GetMapping("myTask")
    public AjaxResult myTask() {
        //获取当前登录用户的信息
        Object username = JWTUtil.parseToken(request.getHeader("Token")).getPayload("username");

        //查询我的代办
        List<Task> taskList = taskService.createTaskQuery().processDefinitionKey("hetong").taskAssignee(username.toString()).list();
        List<HtContract> htContractList = new ArrayList<>();
        taskList.forEach(task->{
            //同时返回工作实列信息，也要返回合同信息
            String businessKey = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult().getBusinessKey();
            HtContract htContract = contractService.getById(businessKey);
            htContract.setTaskId(task.getId());
            htContract.setTaskName(task.getName());
            htContractList.add(htContract);
        });
        return AjaxResult.success(htContractList);
    }

    @Autowired
    ProcessEngine processEngine;

    /**
     * 审核
     * @param htContract
     * @return
     */
    @GetMapping("complete")
    public AjaxResult complete(HtContract htContract) {
        Map<String, Object> map = new HashMap<>();
        map.put("result", "0");
        taskService.complete(htContract.getTaskId(), map);
        return AjaxResult.success();
    }





}
